<template>
  <div class="w-screen h-screen bg-white px-[346px] py-6">
    <!-- 顶部四个圆环 -->
    <div class="flex justify-center items-center gap-8 mb-8">
      <!-- 平均温度 -->
      <div class="relative w-32 h-32">
        <svg viewBox="0 0 100 100" class="w-full h-full">
          <circle cx="50" cy="50" r="40" fill="none" stroke="#e5e7eb" stroke-width="10" />
          <circle
            cx="50"
            cy="50"
            r="40"
            fill="none"
            stroke="#ef4444"
            stroke-width="10"
            stroke-dasharray="251.2"
            :stroke-dashoffset="dashOffsetTemp"
            transform="rotate(-90 50 50)"
          />
          <text x="50" y="50" text-anchor="middle" dominant-baseline="central" font-size="24" fill="#1f2937">
            {{ avgTemp }}°
          </text>
          <text x="50" y="70" text-anchor="middle" font-size="12" fill="#6b7280">平均温度</text>
        </svg>
        <div class="absolute top-0 left-0 w-full h-full flex items-center justify-center">
          <div class="text-xs text-gray-500">{{ tempMin }}°</div>
        </div>
        <div class="absolute bottom-0 right-0 w-full h-full flex items-center justify-center">
          <div class="text-xs text-gray-500">{{ tempMax }}°</div>
        </div>
      </div>

      <!-- 相对湿度 -->
      <div class="w-32 h-32 flex items-center justify-center bg-blue-100 rounded-full">
        <div class="text-center">
          <div class="text-xl font-bold text-blue-700">{{ humidity }}%</div>
          <div class="text-sm text-blue-600">相对湿度</div>
        </div>
      </div>

      <!-- 风速 -->
      <div class="w-32 h-32 flex items-center justify-center bg-gray-100 rounded-full">
        <div class="text-center">
          <div class="text-xl font-bold text-gray-700">{{ windSpeed }} km/h</div>
          <div class="text-sm text-gray-600">风</div>
        </div>
      </div>

      <!-- 空气质量 -->
      <div class="w-32 h-32 flex items-center justify-center bg-green-100 rounded-full">
        <div class="text-center">
          <div class="text-xl font-bold text-green-700">{{ airQuality }}</div>
          <div class="text-sm text-green-600">优</div>
        </div>
      </div>
    </div>

    <!-- 最近十天天气（横向表格） -->
    <div class="mb-8">
      <h2 class="text-center text-lg font-semibold mb-4">洪山区最近十天天气</h2>
      <div class="overflow-x-auto">
        <table class="w-full border-collapse">
          <thead>
            <tr>
              <th class="text-center py-2 bg-gray-100">日期</th>
              <th class="text-center py-2 bg-gray-100">最高温度</th>
              <th class="text-center py-2 bg-gray-100">最低温度</th>
              <th class="text-center py-2 bg-gray-100">平均温度</th>
              <th class="text-center py-2 bg-gray-100">降水量</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(day, index) in recentDays" :key="index">
              <td class="text-center py-2">{{ day.date }}</td>
              <td class="text-center py-2">{{ day.tempMax }}°</td>
              <td class="text-center py-2">{{ day.tempMin }}°</td>
              <td class="text-center py-2">{{ day.avgTemp }}°</td>
              <td class="text-center py-2">{{ day.precip }}mm</td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>

    <!-- 温度变化折线图 -->
    <div class="mb-8">
      <h2 class="text-center text-lg font-semibold mb-4">洪山区最近十天温度变化</h2>
      <div ref="chartRef" class="w-full h-80 bg-gray-50 rounded-lg"></div>
    </div>
  </div>
</template>

<script setup>
import axios from "axios";
import { ref, onMounted } from "vue";

// 数据响应式变量
const userLatitude = ref(null);
const userLongitude = ref(null);

// 最近十天数据
const recentDays = ref([]);

// 顶部指标
const tempMax = ref(37);
const tempMin = ref(26);
const avgTemp = ref((37 + 26) / 2);
const humidity = ref(90);
const windSpeed = ref(6);
const airQuality = ref("30");

// 圆环进度计算（平均温度）
const dashOffsetTemp = ref(251.2 - (avgTemp.value / 40) * 251.2);

// 图表容器
const chartRef = ref(null);

// 初始化定位
window.navigator.geolocation.getCurrentPosition(
  (position) => {
    userLatitude.value = position.coords.latitude.toFixed(2);
    userLongitude.value = position.coords.longitude.toFixed(2);
    fetchRecentTenDaysWeather(userLongitude.value, userLatitude.value);
  },
  (error) => {
    console.log("定位失败:", error);
  },
  { enableHighAccuracy: true }
);

// 获取最近十天天气数据
async function fetchRecentTenDaysWeather(longitude, latitude) {
  const host = "https://p76yvxv44n.re.qweatherapi.com";
  const token =
    "Bearer eyJhbGciOiJFZERTQSIsImtpZCI6Iks0NUY1R0pRTVAifQ.eyJzdWIiOiI0OVRORjZRRUpWIiwiaWF0IjoxNzU3NTcwODgyLCJleHAiOjE3NTc2NTcyODJ9.tgyV0Ric5fuBRXxJjsF-p9k9qafhmprj7L-49FibuLDxj6iWMUh4VAjYrC7UJ-kFpo8kawH-2OLa20SI1h-ICQ";

  try {
    // 获取城市ID
    const geoResponse = await axios.get(`/api/geo/v2/city/lookup`, {
      params: { location: `${longitude},${latitude}` },
      headers: { Authorization: token },
    });

    const locationId = geoResponse.data.location[0].id;

    // 获取最近10天日期
    const today = new Date();
    const dates = [];
    for (let i = 9; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(date.getDate() - i-1);
      const ymd = date.toISOString().split('T')[0];
      dates.push(ymd);
    }

    // 并发请求
    const promises = dates.map(async (date) => {
      const formattedDate = date.replace(/-/g, '');
      try {
        const response = await axios.get(`${host}/v7/historical/weather`, {
          params: {
            location: locationId,
            date: formattedDate,
          },
          headers: { Authorization: token },
        });
        if (response.data.code === "200") {
          return {
            date: date,
            tempMax: response.data.weatherDaily.tempMax,
            tempMin: response.data.weatherDaily.tempMin,
            avgTemp: ((parseInt(response.data.weatherDaily.tempMax) + parseInt(response.data.weatherDaily.tempMin)) / 2).toFixed(1),
            precip: response.data.weatherDaily.precip,
          };
        }
      } catch (error) {
        console.warn(`获取 ${date} 失败:`, error);
        return null;
      }
    });

    const results = await Promise.all(promises);
    recentDays.value = results.filter(item => item !== null);

    // 更新顶部指标（取最新一天）
    const latestDay = recentDays.value[0];
    tempMax.value = parseInt(latestDay.tempMax);
    tempMin.value = parseInt(latestDay.tempMin);
    avgTemp.value = (tempMax.value + tempMin.value) / 2;
    humidity.value = parseInt(latestDay.humidity || 90);
    windSpeed.value = parseInt(latestDay.windSpeed || 6);
    airQuality.value = "30"; // 暂定为优

    // 更新圆环进度
    dashOffsetTemp.value = 251.2 - (avgTemp.value / 40) * 251.2;

    // 渲染图表
    renderChart();
  } catch (error) {
    console.error("获取最近十天天气失败:", error);
  }
}

// 渲染 ECharts 图表
function renderChart() {
  if (!window.ECharts) {
    console.warn("ECharts 未加载");
    return;
  }

  const myChart = window.ECharts.init(chartRef.value);
  const data = recentDays.value;

  const dates = data.map(d => d.date);
  const maxTemps = data.map(d => parseFloat(d.tempMax));
  const minTemps = data.map(d => parseFloat(d.tempMin));
  const avgTemps = data.map(d => parseFloat(d.avgTemp));

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['最高温度', '最低温度', '平均温度']
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '温度 (°C)',
      min: 0,
      max: 40,
      interval: 10
    },
    series: [
      {
        name: '最高温度',
        type: 'line',
        data: maxTemps,
        lineStyle: { color: '#ef4444' },
        areaStyle: { color: '#ef4444', opacity: 0.1 }
      },
      {
        name: '最低温度',
        type: 'line',
        data: minTemps,
        lineStyle: { color: '#3b82f6' },
        areaStyle: { color: '#3b82f6', opacity: 0.1 }
      },
      {
        name: '平均温度',
        type: 'line',
        data: avgTemps,
        lineStyle: { color: '#f59e0b' },
        areaStyle: { color: '#f59e0b', opacity: 0.1 }
      }
    ]
  };

  myChart.setOption(option);
}
</script>
